import Dep from './dep'

export default class Observer {
  constructor(data) {
    this.walk(data);
  }
  walk(data) {
    if (typeof data === 'object') {
      for (const key in data) {
        if (data.hasOwnProperty(key)) {
          const value = data[key];
          this.defineReactive(data, key, value)
        }
      }
    }
  }
  defineReactive(obj, key, val) {
    const self = this
    const dep = new Dep()
    this.walk(val)
    Reflect.defineProperty(obj, key, {
      enumerable: true,
      configurable: true,
      get() {
        Dep.target && dep.addSub(Dep.target)
        return val
      },
      set(newValue) {
        if (newValue !== val) {
          val = newValue
          self.walk(val)
          dep.notify()
        }
      }
    })
  }
}
